<template>
	<v-layout type="main">
		<!-- <p class="page-title">模型仓库</p> -->

		<div class="detail-box">
			<!-- <div class="rollback" @click="$router.push('/model')"> -->
			<div class="rollback" @click="$router.go(-1)">
				<img src="~@/assets/img/prev.png" alt="" />
				<span>返回</span>
			</div>

			<div class="code-description">
				<div class="code-desc-header">
					<div class="title">
						<div class="title-header">
							<span>{{ detailData.name }}</span>
						</div>

						<div class="code-tags">
							<div class="user-tag tag">
								<img src="~@/assets/img/user.png" alt="" />
								{{ detailData.create_user && (detailData.create_user.nick_name || detailData.create_user.username) }}
							</div>

							<div class="version-tag tag">
								<div class="ver-title">
									<img src="~@/assets/img/branch.png" alt="" />
									<span>版本 {{ version.version }}</span>
									<i class="el-icon-arrow-down el-icon--right"></i>
								</div>
								<div class="content">
									<div class="ver-item" v-for="item in versionOptions" :key="item.id" @click="dropdownChange(item)">
										{{ item.version }}
									</div>
								</div>
							</div>

							<div class="time-tag tag">
								<span>创建时间：</span>
								{{ detailData.create_time }}
							</div>

							<div class="time-tag tag">
								<span>更新时间：</span>
								{{ detailData.update_time }}
							</div>
						</div>
					</div>
				</div>

				<!-- <div class="desc-container">
          <el-input type="textarea" placeholder="暂无描述信息" :autosize="{ minRows: 4, maxRows: 4 }" disabled
            v-model="detailData.desc" style="cursor: pointer" />
        </div> -->
			</div>

			<div class="alick-handle-btns">
				<el-button
					class="handle-btn"
					type="primary"
					size="medium"
					@click="toSource"
					v-show="detailData && detailData.business_id"
				>
					来源
				</el-button>

				<el-button class="handle-btn" type="success" size="medium" @click="addModelVersion">
					新增版本
				</el-button>

				<!--        <el-popover placement="bottom-end" width="80" trigger="hover">-->
				<!--          <div class="alick-popover-handle-btns">-->
				<!--            <a class="handle-btn" href="javascript:;" @click="modelEvaluate">模型评估</a>-->
				<!--            <a class="handle-btn" href="javascript:;" @click="modelTest">模型测试</a>-->
				<!--            <a class="handle-btn" href="javascript:;" @click="exportMarketModel">发布到AI市场</a>-->
				<!--          </div>-->
				<!--          &lt;!&ndash; <a class="handle-btn" href="javascript:;" slot="reference">更多</a> &ndash;&gt;-->
				<!--          <el-button class="handle-btn" type="warning" size="medium" slot="reference">更多</el-button>-->
				<!--        </el-popover>-->
				<el-button
					class="handle-btn"
					size="medium"
					icon="el-icon-s-promotion"
					type="success"
					href="javascript:;"
					@click="exportMarketModel"
					>发布到AI市场
				</el-button>
			</div>
		</div>

		<!-- <div class="detail-box" v-if="!$route.meta.hideDetails">
      <div class="pic">
        <v-image class="avatar" :src="detailData.avatar" alt="" />
      </div>
      <div class="word">
        <h3 class="title">
          <h3 class="info-title"> {{ detailData.name }}<i class="el-icon-edit-outline alick-btn-edit"
              @click="updateBase" /></h3>
          <el-button class="back" type="text" icon="el-icon-right" @click="$router.push({ path: '/model' })" />
        </h3>

        <div class="desc-container">
          <el-input type="textarea" placeholder="暂无描述信息" :autosize="{ minRows: 4, maxRows: 4 }" disabled v-model="str"
            style="cursor: pointer" />
        </div>

        <div class="code-info">
          <ul class="info-item">
            <li>
              <span class="key">别名： </span>
              <span class="val">{{ detailData.alias }}</span>
            </li>
            <li>
              <span class="key"> 创建人： </span>
              <span class="val">
                {{ detailData.create_user && (detailData.create_user &&
                  detailData.create_user.nick_name ||
                  detailData.create_user && detailData.create_user.username) }}
              </span>
            </li>
            <li>
              <span class="key">创建时间： </span>
              <span class="val">{{ detailData.create_time }}</span>
            </li>
          </ul>
        </div>

        <div class="alick-handle-btns">
          <a v-if="detailData && detailData.business_id" class="handle-btn" href="javascript:;" @click="toSource">来源</a>
          <a class="handle-btn" href="javascript:;" @click="addModelVersion">新增版本</a>
          <el-popover placement="bottom-end" width="80" trigger="hover">
            <div class="alick-popover-handle-btns">
              <a class="handle-btn" href="javascript:;" @click="modelEvaluate">模型评估</a>
              <a class="handle-btn" href="javascript:;" @click="modelTest">模型测试</a>
              <a class="handle-btn" href="javascript:;" @click="exportMarketModel">发布到AI市场</a>
            </div>
            <a class="handle-btn" href="javascript:;" slot="reference">更多</a>
          </el-popover>
        </div>
      </div>
    </div> -->
		<!--
    <div class="select-ver clearfix">
      <span class="label">版本</span>
      <el-select class="select" v-model="version" value-key="id" @change="versionChange">
        <el-option v-for="item in versionOptions" :value="item" :label="item.version" :key="item.id">
        </el-option>
      </el-select>
    </div> -->

		<!-- <p class="commit-info">
      <strong>提交信息：</strong>{{ version.commit_msg }}
    </p> -->
		<!-- <el-radio-group v-model="nowRouter" size="medium" @change="skip" class="nav-alike" v-show="!$route.meta.hideDetails">
      <el-radio-button :label="e.name" v-for="(e, i) in thisRouter" :key="i">
        <span class="nav-alike-item">{{ e.meta.title }}</span>
      </el-radio-button>
    </el-radio-group> -->

		<!-- <div class="tabs-box">
      <el-tabs v-model="nowRouter" @tab-click="skip" v-show="!$route.meta.hideDetails">
        <el-tab-pane :label="e.meta.title" :name="e.name" v-for="(e, i) in thisRouter" :key="i"/>
      </el-tabs>
    </div> -->

		<div class="tabs-left" v-if="thisRouter.length > 1">
			<el-tabs v-model="nowRouter" @tab-click="skip" v-show="!$route.meta.hideDetails">
				<el-tab-pane :label="e.meta.title" :name="e.name" v-for="(e, i) in thisRouter" :key="i" />
			</el-tabs>
		</div>

		<div :class="['layout-content', { 'layout-content-nodetail': $route.meta.hideDetails }]">
			<router-view class="content-detail" :detailData="detailData" v-if="detailData" :version="version" />
		</div>

		<el-dialog :visible.sync="showModelTestDialog" title="模型测试" width="840px">
			<el-form
				class="form myself-form"
				ref="testModelForm"
				:model="testModelForm"
				:rules="modelEvaSubmitRules"
				label-width="120px"
			>
				<div v-if="active == 1">
					<el-form-item label="模型名称" prop="version">
						{{ detailData.name }}
					</el-form-item>
					<el-form-item label="模型版本" prop="version">
						{{ version.version }}
					</el-form-item>
					<el-form-item label="类型" prop="version">
						<el-select
							v-model="testModelForm.type"
							value-key="id"
							@change="modelTestTypeChange"
							style="width:100%;"
							:popper-append-to-body="false"
							popper-class="select-popper"
							placeholder="请选择"
						>
							<el-option v-for="item in modelEvaTyleOptions" :key="item.id" :label="item.name" :value="item">
							</el-option>
						</el-select>
					</el-form-item>
					<el-form-item label="资源组">
						<el-select v-model="node_group_list.product_id" class="full-extent-select">
							<el-option v-for="item in productOptions" :value="item.id" :label="item.name" :key="item.id"> </el-option>
						</el-select>
					</el-form-item>
					<div v-if="showDiv">
						<el-form-item label="评估镜像">
							<el-select v-model="node_group_list.image_id" class="full-extent-select">
								<el-option v-for="item in imageOptions" :value="item.id" :label="item.name" :key="item.id"> </el-option>
							</el-select>
						</el-form-item>
						<el-form-item label="启动命令行" prop="command">
							<el-input type="text" v-model="node_group_list.command" />
						</el-form-item>
					</div>
				</div>
				<div v-if="active == 2">
					<p class="uploader-hint">文件会上传到/workspace目录下</p>
					<el-form-item label="上传文件 " prop=" ">
						<wrapUploader @succeedOver="succeedOver" type="workspace" :biz_id="testModelForm.id" />
					</el-form-item>
				</div>
				<el-form-item label="" v-if="showDiv && active == 1">
					<el-button type="primary" @click="commitModelTest">下一步</el-button>
				</el-form-item>
				<el-form-item label="" v-if="!showDiv || active == 2">
					<el-button type="primary" @click="commitModelTest">确定</el-button>
					<el-button class="none-type" @click="cancelModelTest">取消</el-button>
				</el-form-item>
			</el-form>
		</el-dialog>

		<el-dialog :visible.sync="showModelEvaDialog" title="模型评估" width="840px">
			<el-form
				class="form myself-form"
				ref="evaModelForm"
				:model="evaModelForm"
				:rules="modelEvaSubmitRules"
				label-width="120px"
			>
				<div v-if="active == 1">
					<el-form-item label="模型名称" prop="version">
						{{ detailData.name }}
					</el-form-item>
					<el-form-item label="模型版本" prop="version">
						{{ version.version }}
					</el-form-item>
					<el-form-item label="类型" prop="version">
						<el-select
							v-model="evaModelForm.type"
							value-key="id"
							@change="modelEvaTypeChange"
							style="width:100%;"
							:popper-append-to-body="false"
							popper-class="select-popper"
							placeholder="请选择"
						>
							<el-option v-for="item in modelEvaTyleOptions" :key="item.id" :label="item.name" :value="item">
							</el-option>
						</el-select>
					</el-form-item>
					<el-form-item label="资源组">
						<el-select v-model="node_group_list.product_id" class="full-extent-select">
							<el-option v-for="item in productOptions" :value="item.id" :label="item.name" :key="item.id"> </el-option>
						</el-select>
					</el-form-item>
					<div v-if="showDiv">
						<el-form-item label="评估镜像">
							<el-select v-model="node_group_list.image_id" class="full-extent-select">
								<el-option v-for="item in imageOptions" :value="item.id" :label="item.name" :key="item.id"> </el-option>
							</el-select>
						</el-form-item>
						<el-form-item label="启动命令行" prop="command">
							<el-input type="text" v-model="node_group_list.command" />
						</el-form-item>
					</div>
				</div>
				<div v-if="active == 2">
					<p class="uploader-hint">文件会上传到/workspace目录下</p>
					<el-form-item label="上传文件 " prop=" ">
						<wrapUploader @succeedOver="succeedOver" type="workspace" :biz_id="evaModelForm.id" />
					</el-form-item>
				</div>
				<el-form-item label="" v-if="showDiv && active == 1">
					<el-button type="primary" @click="commitModelEva">下一步</el-button>
				</el-form-item>
				<el-form-item label="" v-if="!showDiv || active == 2">
					<el-button type="primary" @click="commitModelEva">确定</el-button>
					<el-button class="none-type" @click="cancelModelEva">取消</el-button>
				</el-form-item>
			</el-form>
		</el-dialog>

		<!-- <el-dialog :visible.sync="showModelDialog" title="模型" width="840px">
      <el-form class="form myself-form" ref="modelForm" :model="modelForm" :rules="modelSubmitRules" label-width="120px">
        <el-form-item label="范围" prop="visibility">
          <el-radio-group v-model="modelForm.visibility">
            <el-radio :label="0">私有的</el-radio>
            <el-radio :label="1">共享的</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input type="text" v-model="modelForm.name" />
        </el-form-item>
        <el-form-item label="别名" prop="alias">
          <el-input type="text" v-model="modelForm.alias" />
        </el-form-item>
        <el-form-item label="描述" prop="desc">
          <el-input type="textarea" :rows="3" v-model="modelForm.desc" />
        </el-form-item>
        <el-form-item label="配图">
          <media-uploader accept=".jpg,.jpeg,.png,.JPG,.JPEG" :src="modelForm.avatar" @avatarPath="avatarPath" />
        </el-form-item>
        <el-form-item label="标签类型" prop="labels">
          <el-select v-model="modelForm.labels" style="width:100%;" :popper-append-to-body="false"
            popper-class="select-popper" placeholder="请选择">
            <el-option v-for="item in labelDicts" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="commitModel">确定</el-button>
          <el-button class="none-type" @click="cancelModel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog> -->
	</v-layout>
</template>

<script>
import { getModelDetail, putModel } from "@/api/model";
import { getAllModelVersions } from "@/api/modelversion";
import { getMarketModelBySource } from "@/api/marketModel";
import { labelDicts } from "@/utils/maps";
import { getAllProducts } from "@/api/product";
import { getAllImages } from "@/api/image";
import { addModelEvaluatio, getAllModelEvabyModelVersion } from "@/api/modelEva";
import { addModelTest, getAllModelTestbyModelVersion } from "@/api/modelTest";
import { getAllModelEvaluationTypes } from "@/api/modelEvaType";

export default {
	data() {
		return {
			nowRouter: this.$route.name,
			thisRouter: [],
			detailData: {},
			marketForm: {},
			evaModelForm: {},
			testModelForm: {},
			modelForm: {},
			labelDicts,
			active: 1,
			source_version_id: this.$route.query.source_version_id,
			version: { id: null },
			node_group_list: {
				type: 1,
				pod_num: 1,
			},
			versionOptions: [],
			productOptions: [],
			modelEvaTyleOptions: [],
			imageOptions: [],
			maketModel: null,
			showDiv: false,
			showMarketDialog: false,
			showVersionDialog: false,
			showModelTestDialog: false,
			showModelDialog: false,
			showModelEvaDialog: false,
			modelEvaSubmitRules: {},
			modelTestSubmitRules: {},
			marketSubmitRules: {},
			versionSubmitRules: {
				commit_msg: [
					{ required: true, message: "该项为必填项" },
					{ required: true, min: 1, max: 200, message: "长度在1到200个字符" },
				],
			},
			modelSubmitRules: {
				name: [
					{ required: true, message: "该项为必填项" },
					{ required: true, min: 1, max: 40, message: "长度在1到40个字符" },
				],
				alias: [
					{ required: true, message: "该项为必填项" },
					{ required: true, min: 5, max: 40, message: "长度在1到40个字符" },
				],
				desc: [
					{ required: true, message: "该项为必填项" },
					{ required: true, min: 1, max: 200, message: "长度在1到200个字符" },
				],
			},
			visible: false,
		};
	},
	methods: {
		dropdownChange(val) {
			this.version = val;
			this.versionChange();
		},
		skip() {
			let path = `/model/${this.thisRouter.filter((e) => e.name == this.nowRouter)[0].path}`;
			if (path == this.$route.path) return;
			this.$router.push({
				path,
				query: {
					id: this.$route.query.id,
				},
			});
		},
		avatarPath(data) {
			this.modelForm.avatar = data;
		},
		async getAllModelEvaTypes() {
			let res = await getAllModelEvaluationTypes();
			let data = res.data;
			data.push({ name: "自定义", id: "1" });
			this.modelEvaTyleOptions = data;
			console.log(" this.modelEvaTyleOptions", this.modelEvaTyleOptions);
		},
		// 获取资源组选项
		async getProductList() {
			let res = await getAllProducts();
			this.productOptions = res.data;
		},
		// 评估镜像选项
		async getImageList() {
			let res2 = await getAllImages({ visibility: 2, type: 2 });
			this.imageOptions = res2.data;
		},

		modelTestTypeChange() {
			if (this.testModelForm.type.id == "1") {
				this.showDiv = true;
			} else {
				this.showDiv = false;
			}
		},
		toModelTest(id) {
			let query = {
				model_test_id: id,
			};
			this.$router.push({
				path: "/modelTest/code",
				query,
			});
		},
		async modelTest() {
			if (this.version && this.version.id) {
				let ret = await getAllModelTestbyModelVersion(this.version.id);
				if (ret && ret.data) {
					console.log("ret", ret);
					this.toModelTest(ret.data.id);
				} else {
					this.showModelTestDialog = true;
					this.testModelForm.model_id = this.detailData.id;
					this.testModelForm.model_version_id = this.version.id;
				}
			}
		},
		// 新建模型测试
		commitModelTest() {
			if (this.active == 1) {
				this.$refs.testModelForm.validate(async (valid) => {
					if (valid) {
						console.log("");
						console.log("");
						if (this.testModelForm.type.id != "1") {
							// 非自定义
							this.testModelForm.type_id = this.testModelForm.type.id;
							this.testModelForm.node_group_list = [
								{
									image_id: this.testModelForm.type.eva_image_id,
									command: this.testModelForm.type.eva_image.command,
									product_id: this.node_group_list.product_id,
									type: 1,
									pod_num: 1,
								},
							];
						} else {
							this.testModelForm.type_id = this.testModelForm.type.id;
							this.testModelForm.node_group_list = [this.node_group_list];
						}
						let ret = await addModelTest(this.testModelForm);
						this.testModelForm = ret.data;
						if (this.showDiv) {
							this.active = 2;
						} else {
							this.toModelTest(ret.data.id);
						}
					}
				});
			} else {
				this.toModelTest(this.evaModelForm.id);
			}
		},

		cancelModelTest() {
			this.showModelTestDialog = false;
		},

		// 修改模型评估类型
		modelEvaTypeChange() {
			if (this.evaModelForm.type.id == "1") {
				this.showDiv = true;
			} else {
				this.showDiv = false;
			}
		},
		toModelEva(id) {
			let query = {
				model_eva_id: id,
			};
			this.$router.push({
				path: "/modelEva/code",
				query,
			});
		},
		//模型评估
		async modelEvaluate() {
			if (this.version && this.version.id) {
				let ret = await getAllModelEvabyModelVersion(this.version.id);
				if (ret && ret.data) {
					console.log("ret", ret);
					this.toModelEva(ret.data.id);
				} else {
					this.showModelEvaDialog = true;
					this.evaModelForm.model_id = this.detailData.id;
					this.evaModelForm.model_version_id = this.version.id;
				}
			}
		},
		// 新建模型评估
		commitModelEva() {
			if (this.active == 1) {
				this.$refs.evaModelForm.validate(async (valid) => {
					if (valid) {
						console.log("");
						if (this.evaModelForm.type.id != "1") {
							// 非自定义
							this.evaModelForm.type_id = this.evaModelForm.type.id;
							this.evaModelForm.node_group_list = [
								{
									image_id: this.evaModelForm.type.eva_image_id,
									command: this.evaModelForm.type.eva_image.command,
									product_id: this.node_group_list.product_id,
									type: 1,
									pod_num: 1,
								},
							];
						} else {
							this.evaModelForm.type_id = this.evaModelForm.type.id;
							this.evaModelForm.node_group_list = [this.node_group_list];
						}
						let ret = await addModelEvaluatio(this.evaModelForm);
						this.evaModelForm = ret.data;
						if (this.showDiv) {
							this.active = 2;
						} else {
							this.toModelEva(ret.data.id);
						}
					}
				});
			} else {
				this.toModelEva(this.evaModelForm.id);
			}
		},

		cancelModelEva() {
			this.showModelEvaDialog = false;
		},

		async getModelVersions() {
			let ret = await getAllModelVersions({ model_id: this.$route.query.id });
			this.versionOptions = ret.data;

			if (this.source_version_id) {
				for (let model_version of this.versionOptions) {
					if (model_version.id == this.source_version_id) {
						this.version = model_version;
						this.detailData.version = model_version;
						this.detailData = JSON.parse(JSON.stringify(this.detailData));
						break;
					}
				}
			} else {
				if (this.versionOptions.length > 0) {
					if (this.$route.query.version) {
						this.version = this.versionOptions.filter((item) => item.version === this.$route.query.version)[0];
					} else {
						this.version = this.versionOptions[0];
					}
					this.detailData.version = this.version;
					this.detailData = JSON.parse(JSON.stringify(this.detailData));
				}
			}
		},
		versionChange() {
			this.detailData.version = this.version;
			this.detailData = JSON.parse(JSON.stringify(this.detailData));
			console.log("version", this.version);
		},
		async getDetail() {
			if (this.$route.query.id) {
				let res = await getModelDetail({ id: this.$route.query.id });
				this.detailData = res.data;
				this.getModelVersions();
			}
		},

		updateBase() {
			this.showModelDialog = true;
			console.log("detailData", this.detailData);
			this.modelForm = JSON.parse(JSON.stringify(this.detailData));
			this.modelForm.version = null;
		},
		toSource() {
			this.$router.push({ path: "/notebook/code", query: { id: this.detailData.business_id } });
		},
		commitModel() {
			this.$refs.modelForm.validate(async (valid) => {
				if (valid) {
					await putModel(this.modelForm);
					this.detailData = JSON.parse(JSON.stringify(this.modelForm));
					this.showModelDialog = false;
				}
			});
		},
		cancelModel() {
			this.showModelDialog = false;
		},
		addModelVersion() {
			let version = 1;
			if (this.detailData.version_index) {
				version = this.detailData.version_index + 1;
			}
			let query = {
				modelID: this.detailData.id,
				version: version,
			};
			this.$router.push({
				path: "/model/versionsdetail",
				query,
			});
		},
		async exportMarketModel() {
			console.log(this.version);
			if (!this.version || !this.version.id) {
				alert("没有版本");
				return;
			}
			let data = {
				source: this.detailData.id,
			};
			console.log(this.detailData);
			// let res = await getAllMarketModels(data);
			// console.log(res)
			//
			// if (res && res.data) {
			//   let market_model_id
			//   if (res.data.length > 0) {
			//     market_model_id = res.data[0].id
			//   }
			//   let query = {
			//     model_version_id: this.version.id,
			//     market_model_id: market_model_id
			//   }
			//   this.$router.push({
			//     path: '/market/modeldetail',
			//     query
			//   })
			// }
			let res = await getMarketModelBySource(data);
			// let market_model_id = null
			// console.log("res", res)
			// if (res && res.data) {
			//   if (res.data.length > 0) {
			//     market_model_id = res.data.id
			//   }
			// }
			console.log("res2", res);
			let query = {
				model_version_id: this.version.id,
				// market_model_id: market_model_id
				// market_model_id: this.$route.query.id,
				model_id: this.$route.query.id,
			};
			console.log("query", query);
			this.$router.push({
				path: "/market/modeldetail",
				query,
			});
		},
	},
	mounted() {
		let temp = this.$router.options.routes.filter((e) => e.name == "model" && e.children);
		this.thisRouter = temp[0].children.filter((e) => !e.meta.hideDetails);
		this.getDetail();
		this.getImageList();
		this.getProductList();
		this.getAllModelEvaTypes();
	},

	destroyed() {},
};
</script>
<style lang="less" scoped>
@import "~@/assets/css/detail-layout.less";

.el-dropdown-link {
	border: 1px solid rgba(#808080, 0.5);
	padding: 5px 10px;
	border-radius: 10px;
	position: relative;
	padding-left: 28px;
	background: #eee;
	top: 3px;

	span::before {
		content: "";
		width: 16px;
		height: 16px;
		background: url(~@/assets/img/branch.png) no-repeat center;
		background-size: cover;
		margin-top: 3px;
		position: absolute;
		left: 6px;
		top: 4px;
	}
}
</style>
